import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store'
import router from '@/router'// import { remove } from 'nprogress'
import { removeToken } from './auth'
// import { getToken } from '@/utils/auth'

// create an axios instance

const service = axios.create({
  baseURL: '/api', // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 50000 // request timeout
})

// request interceptor  请求拦截
service.interceptors.request.use(
  (config) => {
    // console.log(config, 555)
    // do something before request is sent

    if (store.getters.token) {
      // let each request carry token
      // ['X-Token'] is a custom headers key
      // please modify it according to the actual situation
      config.headers['Authorization'] = 'Bearer ' + store.getters.token
    }
    return config
  },
  (error) => {
    // do something with request error
    // console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor  响应拦截
service.interceptors.response.use(
  (response) => {
    // console.log(response, 7)
    const res = response.data

    if (res.success) {
      // Message({
      //   message: res.message || 'Success',
      //   type: 'success',
      //   duration: 5 * 1000
      // })
      return res
    } else {
      Message({
        message: res.message || 'Error',
        type: 'error',
        duration: 5 * 1000
      })
      return Promise.reject(new Error(res.message || 'Error'))
    }
  },
  (error) => {
    if (error.response.data.code === 10002) {
      removeToken()
      store.commit('user/RESET_STATE')
      // eslint-disable-next-line no-undef
      router.push('/login')
      window.location.reload()
    }
    // console.log('err' + error) // for debug
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service
